from . import news_blue
from flask import render_template,current_app,session,jsonify,request
from info.models import User,News,Category
from info import constants
from info.utils.response_code import RET

# @news_blue.route('/')
# def index():
#     return render_template('news/index.html')


# 右上角登录注册显示
@news_blue.route('/')
def index():
    user_id=session.get('user_id')
    user=None
    if user_id:
        try:
            user=User.query.get(user_id)
        except Exception as e:
            current_app.logger.error(e)
    # 新闻分类展示
    # 在请求根路由的时候去查询新闻分类，并默认设置第1个分类选中
    try:
        category_list=Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询新闻分类失败')
    if not category_list:
        return jsonify(errno=RET.NODATA,errmsg='没有新闻分类数据')
    category_list1=[]
    for category in category_list:
        category_list1.append(category.to_dict())
    # 点击排行
    # 在请求根路由时去数据库查询按点击量排行的10条新闻
    try:
        news_rank=News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception  as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询新闻列表失败')
    if not news_rank:
        return jsonify(errno=RET.NODATA, errmsg='没有新闻列表数据')
    news_list=[]
    for news in news_rank:
        news_list.append(news.to_dict())
    data={
        'user_info':user.to_dict() if user else None,
        'news_list':news_list,
        'category_list1':category_list1
    }
    return render_template('news/index.html',data=data)


@news_blue.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('news/favicon.ico')

@news_blue.route('/news_list')
def get_news_list():
    # 新闻分类id
    cid=request.args.get('cid','1')
    # 页数,默认第一页
    page=request.args.get('page','1')
    # 每页几条数据
    per_page=request.args.get('per_page','10')
    # 转换数据类型
    try:
        cid,page,per_page=int(cid),int(page),int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg='数据转化失败')
    filters=[]
    if cid>1:
        filters.append(News.category_id==cid)
    try:
        paginate=News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,per_page,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询新闻列表数据失败')
    news_list=paginate.items
    total_pages=paginate.pages
    current_page=paginate.page
    news_dict_list=[]
    for news in news_list:
        news_dict_list.append(news.to_dict())

    data={
        'news_dict_list':news_dict_list,
        'total_pages':total_pages,
        'current_page':current_page
    }
    return jsonify(errno=RET.OK,errmsg='OK',data=data)

    pass